
var crypto = require('crypto');

var Class = require('ClassBuilder');

var AESHelper = Class(function( _public ) {

    _public._construct = function( key ) {

        this.key = key || 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
        this.cipherType = 'aes-256-cbc';

    };

    _public.setCipherType = function( type ) {
        this.cipherType = type;
    };

    _public.encrypt = function( input, outputEncoding, key ) {

        var cipherType = this.cipherType;

        input  = input || '';
        key    = key || this.key;
        outputEncoding = outputEncoding || 'binary';

        var iv = new Buffer(16);
        iv.fill(0);

        var output;
        try {

            var cipher = crypto.createCipheriv( cipherType, key, iv );
            output = cipher.update( input, 'utf8', outputEncoding);
            output += cipher.final(outputEncoding);

        } catch(e) {
            output = false;
        }

        return output;

    };

    _public.decrypt = function( input, inputEncoding, key ) {

        var cipherType = this.cipherType;

        input  = (input || '').toString();
        key    = key || this.key;
        inputEncoding = inputEncoding || 'binary';

        var iv = new Buffer(16);
        iv.fill(0);

        var output;
        try {

            var decipher = crypto.createDecipheriv( cipherType, key, iv );
            output = decipher.update( input, inputEncoding, 'binary' );
            output += decipher.final('binary');
            
        } catch(e) {
            console.log(e);
            output = false;
        }

        return output;

    };

});


module.exports = AESHelper;